<?php
/**
 * Description: 申论 - 切磋互评(写作)作业模块
 * User: devforma
 * Date: 16/5/26
 * Time: 12:05
 */

require __DIR__ . '/ProcessExerciseBase.class.php';

class HupingWriteModule extends ProcessExerciseBase {

    /**
     * 设置作业类型
     */
    protected function setExerciseType() {
        $this->data['exercise_type'] = 2;
    }

    /**
     * 设置作业题目
     */
    protected function setExerciseQuestion() {
        global $cmsdb;

        //获取题目和材料
        $questionInfo = $cmsdb->getRow('SELECT `id`, `question`, `answer`, `parent` FROM `original_ztk_shenlun_questions` WHERE `id`=:id', array(':id' => $this->questionIds[0]));
        $materialInfo = $cmsdb->getRow('SELECT `id`, `notice`, `information` FROM `original_ztk_shenlun_questions` WHERE `id`=:id', array(':id' => $questionInfo->parent));

        $this->data['question'] = array(
            'question_id' => (int)$questionInfo->id,
            'notice'      => $materialInfo->notice,
            'material'    => $materialInfo->information,
            'question'    => $this->removeShenlunQNum($questionInfo->question),
            'answer'      => $questionInfo->answer
        );
    }

    /**
     * 设置提交权限
     */
    protected function setSubmitPriv() {
        parent::setSubmitPriv();
    }

    /**
     * 设置用户答案
     */
    protected function setUserAnswer() {
        global $uddb;

        //查询用户做题记录
        $sql = 'SELECT * FROM `history_primary_question_review` WHERE `user_id`=:uid AND `exercise_id`=:eid LIMIT 1';
        $questionRecord = $uddb->getRow($sql, array(':uid' => $this->userId, ':eid' => $this->exerciseId));
        
        if (!empty($questionRecord)) { //有用户答题记录
            $answer = array(
                'origin' => array(
                    'submit_time' => $questionRecord->action_time,
                    'images'      => explode('#', $questionRecord->user_answer)
                ),
                'reviews' => array()
            );

            //获取所有评论过该作业的记录
            $sql = 'SELECT * FROM `history_primary_question_review` WHERE `question_id`=:record_id AND `reviewer_type`=1';
            $allPostil = (array)$uddb->getResults($sql, array(':record_id' => $questionRecord->id));
            if (!empty($allPostil)) {

                //获取学生信息
                $students = array();
                foreach ($allPostil as $postil) {
                    $students[] = $postil->user_id;
                }
                $students = $this->getStudentInfo($students);

                //构造评论信息
                foreach ($allPostil as $postil) {
                    $answer['reviews'][] = array(
                        'student'       => $students[$postil->reviewer_id],
                        'review_time'   => $postil->review_time,
                        'review_postil' => nl2br((string)$postil->review_postil),
                        'review_level'  => $postil->review_content,
                        'score'         => (int)$postil->review_score
                    );
                }
            }

            $answer['is_collected'] = (int)$questionRecord->is_collected;

            $this->data['user_answer'] = $answer;
        }
    }

    /**
     * 检测提交的参数
     * @param array $args 参数
     * @return bool
     */
    public function validateArgs($args) {
        if (!empty($args['image_url']) && !empty($args['question_id'])) {
            $this->submitArgs = $args;
            return true;
        }

        return false;
    }

    /**
     * 提交 - 设置作业状态
     */
    protected function setSubmitStatus() {
        if ($this->exerciseInfo->end_time > $this->now)
            $this->submitExerciseRecord['status'] = 1; //已完成
        else
            $this->submitExerciseRecord['status'] = 5; //过期完成
    }

    /**
     * 提交 - 保存答题记录及设置作业统计信息
     */
    protected function saveQuestionRecordsAndSetSubmitSummary() {
        global $uddb;

        //构造题目记录
        $questionRecord = array(
            'question_id'   => $this->submitArgs['question_id'],
            'exercise_id'   => $this->exerciseId,
            'user_id'       => $this->userId,
            'action_time'   => $this->now,
            'user_answer'   => $this->submitArgs['image_url'],
            'reviewer_type' => 2, //互评写作记录无评论信息
            'status'        => 1
        );
        $uddb->insert('history_primary_question_review', $questionRecord);

        $this->submitExerciseRecord['summary'] = '';
    }


    /**
     * 提交后额外动作
     */
    protected function doExtra() {
        //创建互评任务
        if ($this->submitExerciseRecord['status'] == 1) {
            $this->generateHupingExercise();
        }
    }

    /**
     * 创建互评作业
     */
    private function generateHupingExercise() {
        global $uddb, $cmsdb;

        //根据写作作业查询评论作业
        $sql = 'SELECT `id`, `start_time`, `end_time` FROM `data_primary_exercise` WHERE `type_id`=9 AND `constraint_ids`=:eid';
        $postilExercises = (array)$cmsdb->getResults($sql, array(':eid' => $this->exerciseId));

       foreach ($postilExercises as $postilExercise) {
           //用户-作业 关联
           $hpUserExercise = array(
               'exercise_id' => $postilExercise->id,
               'user_id'     => $this->userId,
               'start_time'  => $postilExercise->start_time,
               'end_time'    => $postilExercise->end_time,
               'status'      => 0,
               'summary'     => ''
           );
           $uddb->insert('history_user_primary_exercise', $hpUserExercise);
       }
    }

    /**
     * 获取学生信息
     *
     * @param array $userIds 用户id数组
     * @return array
     */
    private function getStudentInfo($userIds) {
        global $uddb;

        $userIds = implode(',', $userIds);

        $data = $uddb->getResults("SELECT `user_id`, `nickname`, `avatar` FROM `user_social_info` WHERE `user_id` IN ({$userIds})");

        $list = array();
        foreach ($data as $item) {
            //兼容每日一题的头像保存url
            if (!empty($item->avatar) && strpos($item->avatar, 'http://') === false) {
                $item->avatar = 'http://edu.appublisher.com/user-images/avatar/'.$item->avatar;
            }
            $list[$item->user_id] = array(
                'id'     => (int)$item->user_id,
                'avatar' => (string)$item->avatar,
                'name'   => $item->nickname
            );
        }

        return $list;
    }
}